package org.hackystat.ui.telemetryviewer.gwt.client;

import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Widget;

/**
 * Encapsulates the horizontal time span menu that found at all other widgets.
 *
 * @author Pavel Senin.
 *
 */
public class SpanRangeWidget
    extends Composite implements ClickListener {

  /* the parent widget handler */
  final ChartWidget parent;

  /* item and selected item styles */
  static final String itemStyle = "spanRange-Item";
  static final String selectedItemStyle = "spanRange-Item-selected";

  /* the possible selections */
  private HorizontalPanel spanList = new HorizontalPanel();

  /* old selection handler, short term memory */
  Widget OldSelectionHolder;

  /**
   * Instantiates the span range widget.
   *
   * @param parent the parent widget on which this will be displayed.
   */
  public SpanRangeWidget(ChartWidget parent) {

    spanList.setStyleName("spanRange-List");
    Button fakeButtonRangeLabel = new Button("Range selection:");
    fakeButtonRangeLabel.setStyleName("spanRange-Item-Label");
    spanList.add(fakeButtonRangeLabel);
    this.parent = parent;
    initWidget(spanList);
  }

  /**
   * Adds the particular span instance to the list.
   *
   * @param button the span to add.
   */
  public void addSpan(SpanButton button) {
    button.setStyleName(itemStyle);
    spanList.add(button);
  }

  /** {@inheritDoc} */
  public void onClick(Widget sender) {
    // get this button handler
    SpanButton sb = (SpanButton) sender;
    // "unselect" old selection
    if (null != OldSelectionHolder) {
      OldSelectionHolder.setStyleName(itemStyle);
    }
    sb.setStyleName(selectedItemStyle);
    // memorize new selection
    OldSelectionHolder = sb;

    this.parent.setSpan(sb.getName());
  }
}
